<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

defined('_JEXEC') or die();

class JobBoardModelJASubscriptions extends JModel
{
	
	var $_data;
	var $cate;
	function __construct()
	{
		parent::__construct();

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
		$this->cate =null;
	}
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}


	function &getItem()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = ' SELECT * FROM #__ja_subscriptions '.
					'  WHERE id = '.(int)$this->_id;
			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
		}
		return $this->_data;
	}
	
	function &getTable(){
		global $jbconfig;
		if (array_key_exists('dbo', $jbconfig))  {
			$db =& $jbconfig['dbo'];
		} else {
			$db = & JFactory::getDBO();
		}
		
		 if($this->_table == null){
		 	require_once(JPATH_SITE.DS.'components'.DS.JBCOMNAME.DS.'tables/jasubscriptions.php');
        	$this->_table = &JTable::getInstance('JASubscriptions', 'JobBoardTable');
		}
		$this->_table = new JobBoardTableJASubscriptions($db);
		return $this->_table;
	}
	// get all categories for parrent cat
	// save a category when edit or new.
	function store()	{
		
		$db		 =& JFactory::getDBO();
		$post		= JRequest::get( 'post' );
		/**
		 * add permision change
		 */
		$permssion	=	0;
		$subpermissions	=	$post['sub_permssion'];		
		
		if($subpermissions)
		{
			foreach ($subpermissions as $per){				
				$permssion	=	(intval($permssion)|intval($per));
			}
		}
		
		$post['permission']		=	$permssion;
		$post['description'] = JRequest::getVar( 'description', '', 'post', 'string', JREQUEST_ALLOWRAW );
		
		jimport('joomla.filesystem.file');
		
		if(isset($post['remove_img']) && $post['remove_img']){
			$old_img = JRequest::getVar('image_old','');
				
			if($old_img && JFile::exists($dest.$old_img))
				JFile::delete($dest.$old_img);
			$post['image'] = '';
		}
		
		if(isset($_FILES['img_sub']['name']) && $_FILES['img_sub']['name']!=''){
			
			$dest = JPATH_COMPONENT_SITE."/images/icons/subscriptions/";
			
			if(JFile::upload($_FILES['img_sub']['tmp_name'], $dest.$_FILES['img_sub']['name'])){
				$post['image'] = $_FILES['img_sub']['name'];
				
				$old_img = JRequest::getVar('image_old','');
				
				if($old_img && JFile::exists($dest.$old_img))
					JFile::delete($dest.$old_img);
			}			
		}
		
		$row =& $this->getTable();

		if (!$row->bind($post)) {
			$this->setError($db->getErrorMsg());
			return  false;
			
		}

		// Make sure the hello record is valid
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		
		$row->sub_code_get();
		
		if (!$row->store()) 
		{
			$this->setError( $row->getErrorMsg() );
		}					
			
		return $row->id;
		
	}
	// method delete one or more categories selected
	function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );
		JArrayHelper::toInteger($cids, array(0));
		$row =& $this->getTable();

		if (count( $cids ))
		{
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
			}						
		}
		return true;
	}
	
	function getcountsub()
	{
		$db	=& JFactory::getDBO();
		$param = $this->getvar();
		$filter_order	= $param['filter_order'];
		$filter_order_Dir	= $param['filter_order_Dir']; 
		$search		= $param['search'];
		$search	= JString::strtolower( $search );
		$where = '  WHERE 1 ';
		$filter ='';
		if ($search) {
			$filter = ' AND LOWER(s.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
			}
		$query = 'SELECT COUNT(*)'
	. ' FROM #__ja_subscriptions s'
	;
		$query .=$where .$filter;
		$db->setQuery( $query );
		$total = $db->loadResult();
		return $total;
	}
	
	function getvar()
	{
		global $mainframe, $option;
		$list = array();
		$list['filter_order'] 		= $mainframe->getUserStateFromRequest( $option.'.filter_order',	'filter_order',	's.cost',	'cmd' );
		$list['filter_order_Dir'] 	= $mainframe->getUserStateFromRequest( $option.'.filter_order_Dir',	'filter_order_Dir',	'',				'word' );
		$list['limit'] 		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$list['limitstart'] 	= $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
		$list['search'] 	= $mainframe->getUserStateFromRequest( $option.'.search',						'search',			'',				'string' );
		$list['option'] 	= $option;
		return  $list;
	}
	
	// get all subscriptions
	function getSubscriptions()
	{
		// Lets load the data if it doesn't already exist
		$db	=& JFactory::getDBO();
		$param = $this->getvar();
		$filter_order	= $param['filter_order'];
		$filter_order_Dir	= $param['filter_order_Dir']; 
		$limit		= $param['limit'];
		$limitstart	= $param['limitstart']; 
		$search		= $param['search'];
		$search	= JString::strtolower( $search );
		$where = '  WHERE 1 ';
		$filter ='';
		
		$filter_arr =array('s.title','s.published','s.require_approved','s.price','s.id');
		if(!in_array($filter_order,$filter_arr))
		{
			$filter_order = 's.price';
		}	
		if ($search) {
			$filter = ' AND LOWER(s.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
		}
		$total = $this->getcountsub();
			
		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
		$order 			= ' ORDER BY  '. $filter_order .' '. $filter_order_Dir ;
		$query = 'SELECT  s.* FROM #__ja_subscriptions  s '
				.$where .$filter. $order
				;
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
		
		$rows = $db->loadObjectList();
		return $rows;
	}
	
	// published categories
	function dopublish( $publish =1, $field='published')
	{
		$db		=& JFactory::getDBO();
		
		$ids = JRequest::getVar('cid', array());
		JArrayHelper::toInteger($cid, array(0));
		$ids = implode( ',', $ids );
		
		$query = "UPDATE #__ja_subscriptions"
		. "\n SET $field = " . intval( $publish )
		. "\n WHERE id IN ( $ids )"
		;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}
	
	function mailSubscriptionExpired($userID, $supscriptionID, $transactionID, $email_template = 'SubscriptionExpired'){
		$emailConfig = JobBoardConstant::getEmailConfig ();
		$user = JFactory::getUser ();
		
		$arr_link = array ();
		$profile = getProfileFromUserId ( $userID );
		if($profile){
			$arr_link ['ja_profiles'] = $profile->id;
		}
		$resume = getResumeFromUserId($userID);
		if($resume){
			$arr_link ['ja_resumes'] = $resume->id;
		}
			
		$arr_link ['users'] = $userID;
		$arr_link ['ja_subscriptions'] = $supscriptionID;
		$arr_link ['ja_transactions'] = $transactionID;
		
		$mail = get_EmailTemplate ( $arr_link, $email_template );
		if(empty($mail->EmailFromAddress))
			$mail->EmailFromAddress = $emailConfig ['admin_email'];
		if(empty($mail->EmailFromName))
			$mail->EmailFromName = $emailConfig ['admin_name'];
		if ($mail)
			sendMail( $user->email, $user->name, $mail->subject, $mail->content, '', $mail->EmailFromAddress, $mail->EmailFromName );
	}
}
